﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Douban.Modules.Conversation.Views;
using Douban.Core;
using Douban.Api;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Composite.Events;
using System.Windows.Data;

namespace Douban.Modules.Conversation.ViewModels
{
    public class CaptchaViewModel : ObservableObject, ICaptchaViewModel
    {
        private string _captchaString;

        public CaptchaViewModel(ICaptchaView view)
        {
            View = view;
            View.Context = this;
            View.SendCaptchaKeyDown += SendCaptchaKeyDown;
        }

        #region ICaptchaViewModel Members

        public ICaptchaView View { get; set; }

        public string CaptchaToken { get; set; }

        public string CaptchaUrl { get; set; }

        public string CaptchaString
        {
            get { return _captchaString; }
            set
            {
                if (_captchaString != value)
                {
                    _captchaString = value;
                    NotifyPropertyChanged("CaptchaString");
                }
            }
        }

        private ICommand _sendCaptchaCommand;

        public ICommand SendCaptchaCommand
        {
            get
            {
                if (_sendCaptchaCommand == null)
                    _sendCaptchaCommand = new DelegateCommand<object>(obj => OnSendCaptcha());

                return _sendCaptchaCommand;
            }
        }

        public event EventHandler SendCaptcha;

        #endregion

        private void OnSendCaptcha()
        {
            BindingExpression binding = View.GetBindingCaptchaString();
            binding.UpdateSource();

            if (SendCaptcha != null)
                SendCaptcha(this, new EventArgs());

            View.CloseView();
        }

        private void SendCaptchaKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                OnSendCaptcha();
        }
    }
}
